
//
//  ViewController.m
//  Trip
//
//  Created by dllo on 15/7/17.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "TravelPushViewController.h"
#import "AFNetworking.h"
#import "TravelNotesParser.h"
#import "TravelNotesAll.h"
#import "UIImageView+WebCache.h"
#import "TravelPushTableViewCell.h"
#import "Database.h"
#import <ShareSDK/ShareSDK.h>
@interface TravelPushViewController ()<UITableViewDataSource, UITableViewDelegate, UIAlertViewDelegate, UIScrollViewDelegate>
{
    UITableView *tableViewWhole;
    UITableView *GeneralTableView;
    UIImageView *iView;
}
@property (nonatomic, retain) NSMutableArray *arrayData;
@property (nonatomic, retain) UIButton *generalBtn;
@property (nonatomic, assign) NSInteger sepLength;
@property (nonatomic, retain) UITapGestureRecognizer *tapGesture;
@property (nonatomic, retain) NSThread *thread;
@property (nonatomic, retain) UIButton *shareBtn;
@property (nonatomic, retain) UIButton *collectBtn;
@property (nonatomic, retain) UIView *headerView;
@property (nonatomic, retain) UIImageView *img;
@end

@implementation TravelPushViewController

static NSString *identifier = @"cell";
- (void)dealloc
{
    [_arrayData release];
    [_generalBtn release];
    [_tapGesture release];
    [_thread release];
    [_shareBtn release];
    [_collectBtn release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBarHidden = NO;
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 44)];
    view.backgroundColor = [UIColor clearColor];
    [self.view addSubview:view];
    [view release];
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"Navbar_mask"] forBarMetrics:UIBarMetricsDefault];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"BackBorderBarButton"] style:UIBarButtonItemStylePlain target:self action:@selector(back:)];
    self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];

    // 初始化controller
    self.tabBarController.tabBar.hidden  = YES;
    self.tabBarController.tabBar.translucent = YES;
    self.arrayData = [NSMutableArray array];
    
    self.shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *shareBtn = [UIImage imageNamed:@"ShareBorderBarButton"];
    shareBtn = [shareBtn imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [self.shareBtn setImage:shareBtn forState:UIControlStateNormal];
    self.collectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *collectBtn = [UIImage imageNamed:@"FavoriteBorderBarButton"];
    collectBtn = [collectBtn imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [self.collectBtn setImage:collectBtn forState:UIControlStateNormal];
    self.shareBtn.frame = CGRectMake(self.view.frame.size.width - 80, 5, 30, 30);
    self.collectBtn.frame = CGRectMake(self.view.frame.size.width - 46, 3, 32, 32);
    [self.shareBtn addTarget:self action:@selector(share) forControlEvents:UIControlEventTouchUpInside];
    [self.collectBtn addTarget:self action:@selector(collect) forControlEvents:UIControlEventTouchUpInside];
    self.collectBtn.hidden = NO;
    self.shareBtn.hidden = NO;
    self.collectBtn.enabled = NO;
    self.shareBtn.enabled = NO;
    
    [self judgeCollectState];
    
    // 定义菊花控件
    UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    [self.view addSubview:activityIndicator];
    activityIndicator.color = [UIColor grayColor];
    activityIndicator.center = self.view.center;
    [activityIndicator release];
    [activityIndicator startAnimating];
    
    [self.navigationController.navigationBar addSubview:self.shareBtn];
    [self.navigationController.navigationBar addSubview:self.collectBtn];
    
    // 网络请求
    NSString *str = [NSString stringWithFormat:@"http://chanyouji.com/api/trips/%ld.json", (long)self.number];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", nil]];
    [manager GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *data = operation.responseData;
        self.arrayData = [TravelNotesParser getParser:data];
        [self tableViewDidLoad];
        [activityIndicator stopAnimating];
        self.collectBtn.enabled = YES;
        self.shareBtn.enabled = YES;
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
}
- (void)back:(UIButton *)btn
{
    GeneralTableView.hidden = YES;
    self.collectBtn.hidden = YES;
    self.shareBtn.hidden = YES;
    [self.navigationController popToRootViewControllerAnimated:YES];
}
//- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
//{
//    if (alertView.tag == 1) {
//        return;
//    }
//    // 定义菊花控件
//    UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
//    [self.view addSubview:activityIndicator];
//    activityIndicator.color = [UIColor grayColor];
//    activityIndicator.center = self.view.center;
//    [activityIndicator release];
//    [activityIndicator startAnimating];
//
//    NSString *path = [URLPath travelNotesSecondURL];
//    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//    // foriegn跳转页面过来
//    if (self.chooseView == 1) {
//        path = @"http://chanyouji.com/api/plans/";
//    } else {
//        path = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    }
//
//    NSString *str = [path stringByAppendingFormat:@"%ld.json", self.number];
//
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//
//    [manager.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", nil]];
//
//
//    [manager GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSData *data = operation.responseData;
//        self.arrayData = [TravelNotesSecondParser getParser:data];
//        [self tableViewDidLoad];
//        [activityIndicator stopAnimating];
//
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        [activityIndicator stopAnimating];
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接失败" message:nil delegate:self cancelButtonTitle:@"重新连接" otherButtonTitles:nil, nil];
//        alert.delegate = self;
//        [alert show];
//    }];
//
//}

- (void)share
{
    //创建弹出菜单容器
    id<ISSContainer> container = [ShareSDK container];
    id<ISSContent> publishContent = [ShareSDK content:@"分享内容:"
                                       defaultContent:@"测试一下"
                                                image:nil
                                                title:@"ShareSDK"
                                                  url:@"http://www.mob.com"
                                          description:@"这是一条测试信息"
                                            mediaType:SSPublishContentMediaTypeNews];
    
    //弹出分享菜单
    [ShareSDK showShareActionSheet:container
                         shareList:nil
                           content:publishContent
                     statusBarTips:YES
                       authOptions:nil
                      shareOptions:nil
                            result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                                
                                if (state == SSResponseStateSuccess)
                                {
                                    NSLog(NSLocalizedString(@"TEXT_ShARE_SUC", @"分享成功"));
                                }
                                else if (state == SSResponseStateFail)
                                {
                                    NSLog(NSLocalizedString(@"TEXT_ShARE_FAI", @"分享失败,错误码:%d,错误描述:%@"), [error errorCode], [error errorDescription]);
                                }
                            }];
}

- (void)collect
{
    NSArray *array = [Database selectData];
    int i = 0;
    NSArray *arra = [self.arrayData firstObject];
    NSArray *arr = [arra objectAtIndex:0];
    TravelNotesAll *travelNotesModel = [arr firstObject];
    for (DbModel *model in array) {
        if (model.titleId == self.number) {
            i = 1;
            break;
        }
    }
    if (i == 1) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"您已经收藏过此篇游记!" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil , nil];
        alert.tag = 1;
        [alert show];
    } else {
        DbModel *model = [DbModel getDbModel];
        model.title = travelNotesModel.name;
        model.titleId = self.number;
        model.choose = 0;
        model.imageURL = travelNotesModel.front_cover_photo_url;
        [Database insertValue:model];
        UIImage *collectBtn = [UIImage imageNamed:@"FavoritedBorderBarButton"];
        collectBtn = [collectBtn imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        [self.collectBtn setImage:collectBtn forState:UIControlStateNormal];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"收藏成功!" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil , nil];
        alert.tag = 1;
        [alert show];
    }
}

#pragma -mark 隐藏目录
- (void)beginTouch
{
    [UIView animateWithDuration:0.5 animations:^{
        self.generalBtn.frame = CGRectMake(20, self.view.frame.size.height - 60, 40, 40);
        GeneralTableView.frame = CGRectMake(-200, 0, 200, self.view.frame.size.height);
    }];
}
- (void)tableViewDidLoad
{
    tableViewWhole = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    [self.view addSubview:tableViewWhole];
    [tableViewWhole release];
    tableViewWhole.delegate = self;
    tableViewWhole.dataSource = self;
    [tableViewWhole setBounces:NO];
    tableViewWhole.tag = 1;
    tableViewWhole.contentInset = UIEdgeInsetsMake(0, 0, 70, 0);
    
    // 添加点击

    self.tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(beginTouch)];
    [tableViewWhole addGestureRecognizer:self.tapGesture];
    self.tapGesture.enabled = YES;
    
    // 呼出概况栏
    self.generalBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.generalBtn.backgroundColor = [UIColor clearColor];
    self.generalBtn.frame = CGRectMake(20, self.view.frame.size.height - 60, 40, 40);
    [self.view addSubview:self.generalBtn];
    [self.view bringSubviewToFront:self.generalBtn];
    [self.generalBtn addTarget:self action:@selector(getGeneral) forControlEvents:UIControlEventTouchUpInside];
    self.generalBtn.layer.cornerRadius = 20;
    self.generalBtn.layer.masksToBounds = YES;
    self.generalBtn.layer.borderColor = [UIColor whiteColor].CGColor;
    self.generalBtn.layer.borderWidth = 2;
    [self.generalBtn setImage:[UIImage imageNamed:@"OutlineButtonHighlight"] forState:UIControlStateNormal];
    
    // 添加第二个tableview
    GeneralTableView = [[UITableView alloc] initWithFrame:CGRectMake(-200, 64, 200, self.view.frame.size.height) style:UITableViewStylePlain];
    GeneralTableView.contentInset = UIEdgeInsetsMake(0, 0, 70, 0);
    [self.view addSubview:GeneralTableView];
    [GeneralTableView release];
    GeneralTableView.alpha = 0.9;
    GeneralTableView.backgroundColor = [UIColor blackColor];
    GeneralTableView.delegate = self;
    GeneralTableView.dataSource = self;
    GeneralTableView.tag = 2;
    GeneralTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    GeneralTableView.hidden = YES;
    
    self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200)];
    NSArray *array = [self.arrayData firstObject];
    NSArray *arr = [array objectAtIndex:0];
    TravelNotesAll *model = [arr firstObject];
    iView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.headerView.frame.size.width, self.headerView.frame.size.height)];
    iView.layer.masksToBounds = YES;
    iView.clipsToBounds = YES;
    [iView setContentMode:UIViewContentModeScaleAspectFill];
    [iView setImageWithURL:[NSURL URLWithString:model.front_cover_photo_url] placeholderImage:[UIImage imageNamed:@"place_holder.jpg"]];
    [self.headerView addSubview:iView];
    
    self.img = [[UIImageView alloc] initWithFrame:CGRectMake(0, -(200 - 64), self.view.bounds.size.width, 200)];
    [self.img setImageWithURL:[NSURL URLWithString:model.front_cover_photo_url] placeholderImage:[UIImage imageNamed:@"place_holder.jpg"]];
    [self.view addSubview:self.img];
    self.img.hidden = YES;
    
    CABasicAnimation *animation1 = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    //什么状态开始放大
    animation1.fromValue = [NSNumber numberWithFloat:1];
    //到什么状态结束
    animation1.toValue = [NSNumber numberWithFloat:1.6];
    //动画执行时间
    animation1.duration = 3.0f;
    //是否恢复
    animation1.autoreverses = YES;
    //重复次数
    animation1.repeatCount = NSIntegerMax;
    //把动画添加到layer
    [iView.layer addAnimation:animation1 forKey:@"动画1"];
    tableViewWhole.tableHeaderView = self.headerView;
    [tableViewWhole sendSubviewToBack:tableViewWhole.tableHeaderView];
    
    UIImageView *userImage = [[UIImageView alloc] initWithFrame:CGRectMake(20, 140, 40, 40)];
    [userImage setImageWithURL:[NSURL URLWithString:model.userImage] placeholderImage:nil];
    [self.headerView addSubview:userImage];
    userImage.layer.cornerRadius = 5.0;
    userImage.layer.masksToBounds = YES;
    userImage.layer.borderColor = [UIColor whiteColor].CGColor;
    userImage.layer.borderWidth = 1;
    UILabel *userName = [[UILabel alloc] initWithFrame:CGRectMake(70, 145, self.view.frame.size.width - 70, 30)];
    userName.text = model.name;
    userName.textColor = [UIColor whiteColor];
    userName.font = [UIFont boldSystemFontOfSize:15];
    [self.headerView addSubview:userName];
    [userName release];
    [iView release];
    [_headerView release];

    //    [iView sd_setImageWithURL:[NSURL URLWithString:model.front_cover_photo_url] placeholderImage:[UIImage imageNamed:@"defaultPic"] options:SDWebImageProgressiveDownload completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
    //
    //    }];
    
    //    iView.autoresizingMask = UIViewAutoresizingFlexibleHeight| UIViewAutoresizingFlexibleWidth;
    //    iView.clipsToBounds = YES;
    //    iView.contentMode = UIViewContentModeScaleAspectFill;
    //
    //     _header = [CExpandHeader expandWithScrollView:tView expandView:headerView];
    
}
// 获取第二个tableView
- (void)getGeneral
{
    GeneralTableView.hidden = NO;
    self.tapGesture.enabled = YES;
    [UIView animateWithDuration:0.5 animations:^{
        GeneralTableView.frame = CGRectMake(0, 64, 200, self.view.frame.size.height);
        self.generalBtn.frame = CGRectMake(20, self.view.frame.size.height, 40, 40);
    }];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 1) {
        TravelPushTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[[TravelPushTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] autorelease];
            cell.frame = CGRectMake(cell.frame.origin.x, cell.frame.origin.y, self.view.frame.size.width, cell.frame.size.height);
        }
        cell.titleView.layer.borderColor = nil;
        cell.titleView.layer.borderWidth = 0;
        cell.url.image = nil;
        cell.name_zh_cn.text = nil;
        cell.titleView.image = nil;
        cell.descrip.text = nil;
        cell.titleView.backgroundColor = nil;
        cell.comment.text = nil;
        
        NSArray *array = [self.arrayData objectAtIndex:indexPath.section];
        NSArray *arr = [array objectAtIndex:indexPath.row];
        TravelNotesAll *model = [arr objectAtIndex:2];
        [cell setTravelNotesAll:model];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    } else {
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] autorelease];
        }
        cell.backgroundColor = [UIColor blackColor];
        NSArray *array = [self.arrayData lastObject];
        NSArray *arr = [array objectAtIndex:indexPath.section];
        TravelNotesAll *model = [TravelNotesAll getModel];
        if (indexPath.row == 0) {
            if (arr.count > 0) {
                model = [arr objectAtIndex:indexPath.row];
            }
        } else {
            if (arr.count > 0) {
                model = [arr objectAtIndex:indexPath.row - 1];
            }
        }
        if (indexPath.row == 0) {
            cell.textLabel.textColor = [UIColor whiteColor];
            cell.textLabel.text = [NSString stringWithFormat:@"O   DAY%ld", (long)model.day];
            cell.textLabel.font = [UIFont systemFontOfSize:15];
        } else {
            cell.textLabel.text = [NSString stringWithFormat:@"o   %@", model.entry_name];
            cell.textLabel.textColor = [UIColor whiteColor];
            cell.textLabel.font = [UIFont systemFontOfSize:13];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (tableView.tag == 1) {
        return 30;
    } else {
        return 10;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (tableView.tag == 1) {
        UIView *view = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width - 60, 30)]autorelease];
        view.backgroundColor = [UIColor whiteColor];
        UILabel *dayLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, 70, 30)];
        [view addSubview:dayLabel];
        [dayLabel release];
        UILabel *dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(90, 0, 120, 30)];
        [view addSubview:dateLabel];
        dayLabel.textColor = [UIColor blackColor];
        dateLabel.textColor = [UIColor blackColor];
        [dateLabel release];
        NSArray *array = [self.arrayData objectAtIndex:section];
        NSArray *arr = [array firstObject];
        TravelNotesAll *model = [arr objectAtIndex:2];
        dayLabel.text = [NSString stringWithFormat:@"DAY%ld", (long)model.day];
        dayLabel.font = [UIFont boldSystemFontOfSize:20];
        if (model.trip_date != nil && ![model.trip_date isEqual:[NSNull null]]) {
            dateLabel.text = [NSString stringWithString:model.trip_date];
        }
        return view;
    } else {
        return nil;
    }
}

#pragma -mark cell 点击方法

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 2) {
        NSArray *b = [self.arrayData lastObject];
        NSArray *br = [b objectAtIndex:indexPath.section];
        TravelNotesAll *mo = [TravelNotesAll getModel];
        if (indexPath.row == 0) {
            mo = [br objectAtIndex:indexPath.row];
        } else {
            mo = [br objectAtIndex:indexPath.row - 1];
        }
        NSArray *a = [self.arrayData objectAtIndex:indexPath.section];
        int i = 0;
        for (NSArray *ar in a) {
            TravelNotesAll *model = [ar objectAtIndex:2];
            if (model.entry_name == nil || [model.entry_name isEqual:[NSNull null]] || ![model.entry_name isEqualToString:mo.entry_name]) {
                i++;
            } else {
                break;
            }
        }
        
        if (indexPath.row == 0) {
            NSIndexPath *path = [NSIndexPath indexPathForRow:0 inSection:indexPath.section];
            [tableViewWhole scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionTop animated:YES];
            [UIView animateWithDuration:0.5 animations:^{
                self.generalBtn.frame = CGRectMake(20, self.view.frame.size.height - 50, 40, 40);
                GeneralTableView.frame = CGRectMake(-200, 0, 200, self.view.frame.size.height);
            }];
            
        } else {
            NSIndexPath *path = [NSIndexPath indexPathForRow:i inSection:indexPath.section];
            [tableViewWhole scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionTop animated:YES];
            [UIView animateWithDuration:0.5 animations:^{
                self.generalBtn.frame = CGRectMake(20, self.view.frame.size.height - 50, 40, 40);
                GeneralTableView.frame = CGRectMake(-200, 0, 200, self.view.frame.size.height);
            }];
        }
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    //    } else {
    //        NSArray *array = [self.arrayData objectAtIndex:indexPath.section];
    //        NSArray *arr = [array objectAtIndex:indexPath.row];
    //        TravelNotesSecondModel *model = [arr objectAtIndex:2];
    //        if (model.url != nil && ![model.url isEqual:[NSNull null]]) {
    //            UIActionSheet *action = [[UIActionSheet alloc] initWithTitle:@"保存图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"确定" otherButtonTitles:nil, nil];
    //            [action showFromTabBar:self.tabBarController.tabBar];
    //            self.myPhoto = model.url;
    //        }
    //    }
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        
    } else {
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView.tag == 1) {
        NSArray *array = [self.arrayData objectAtIndex:section];
        return array.count;
    } else {
        NSArray *array = [self.arrayData objectAtIndex:section];
        NSArray *arr = [array lastObject];
        TravelNotesAll *model = [arr objectAtIndex:1];
        if (model.num != 0) {
            return model.num + 1;
        } else {
            return 1;
        }
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.arrayData.count - 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (tableView.tag == 1) {
        NSArray *array = [self.arrayData objectAtIndex:indexPath.section];
        NSArray *arr = [array objectAtIndex:indexPath.row];
        TravelNotesAll *model = [arr objectAtIndex:2];
        // 动态计算label高度
        NSDictionary *dic = [NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:15] forKey:NSFontAttributeName];
        CGRect frame;
        if (model.descrip != nil && ![model.descrip isEqual:[NSNull null]]) {
            frame = [model.descrip boundingRectWithSize:CGSizeMake(self.view.frame.size.width - 20, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        }
        if (model.entry_type == nil || [model.entry_type isEqual:[NSNull null]]) {// 无title
            if ((model.url == nil || [model.url isEqual:[NSNull null]]) && (model.descrip == nil || [model.descrip isEqual:[NSNull null]])) {
                // 都没有
                return 0;
            } else if (model.url != nil && ![model.url isEqual:[NSNull null]] && (model.descrip == nil || [model.descrip isEqual:[NSNull null]])) {
                // 有图无文字
                return ((self.view.frame.size.width - 40) * (model.image_height / (CGFloat)model.image_width)) + 40;
                
            } else if (model.url != nil && ![model.url isEqual:[NSNull null]] && model.descrip != nil && ![model.descrip isEqual:[NSNull null]]) {
                // 有图有文字
                return (frame.size.height + ((self.view.frame.size.width - 20) * (model.image_height / (CGFloat)model.image_width))) + 30;
            } else {
                // 纯文字
                return frame.size.height + 20;
            }
            
        } else if (model.entry_type != nil && ![model.entry_type isEqual:[NSNull null]]) {// 有title
            if ((model.url == nil || [model.url isEqual:[NSNull null]]) && (model.descrip == nil ||[model.descrip isEqual:[NSNull null]])) {
                // 无图无文字
                return 80;
            } else if (model.url != nil && ![model.url isEqual:[NSNull null]] && ((model.descrip == nil || [model.descrip isEqual:[NSNull null]]))) {
                // 有图无文字
                return 70 + ((self.view.frame.size.width - 20) * (model.image_height / (CGFloat)model.image_width));
            } else if (model.url != nil && ![model.url isEqual:[NSNull null]] && model.descrip != nil && ![model.descrip isEqual:[NSNull null]]) {
                // 有图有文字
                return 90 + (frame.size.height + ((self.view.frame.size.width - 20) * (model.image_height / (CGFloat)model.image_width)));
            } else if ((model.url == nil || [model.url isEqual:[NSNull null]]) && model.descrip != nil && ![model.descrip isEqual:[NSNull null]]){
                // 无图有文字
                return 50 + frame.size.height + 20;
            }
        }
    } else if (tableView.tag == 2) {
        return 25;
    }
    return 0;
}
- (void)judgeCollectState
{
    NSArray *array = [Database selectData];
    int i = 0;
    for (DbModel *model in array) {
        if (model.titleId == self.number) {
            i = 1;
            break;
        }
    }
    if (i == 1) {
        UIImage *collectBtn = [UIImage imageNamed:@"FavoritedBorderBarButton"];
        collectBtn = [collectBtn imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        [self.collectBtn setImage:collectBtn forState:UIControlStateNormal];
    } else {
        UIImage *collectBtn = [UIImage imageNamed:@"FavoriteBorderBarButton"];
        collectBtn = [collectBtn imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        [self.collectBtn setImage:collectBtn forState:UIControlStateNormal];
    }
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    for (UIView *aview in self.navigationController.navigationBar.subviews) {
        if ([aview.class isEqual:[UISearchBar class]]) {
            aview.hidden = YES;
        }
    }
    
    if (tableViewWhole.contentOffset.y >= (200 - 64)) {
        //self.img.hidden = NO;
        //tableViewWhole.tableHeaderView = nil;
        //self.navigationController.navigationBar.translucent = YES;
        //tableViewWhole.frame = CGRectMake(0, 64, self.view.bounds.size.width, self.view.bounds.size.height);
    } else if (tableViewWhole.contentOffset.y <= (200 - 64)){
        self.img.hidden = YES;
        tableViewWhole.tableHeaderView = self.headerView;
        tableViewWhole.frame = self.view.frame;
        [tableViewWhole sendSubviewToBack:tableViewWhole.tableHeaderView];

    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end


